package cz.acies.organizer.data.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cz.acies.data.dao.MModelFolderDAO;
import cz.acies.data.persist.TreeNode;
import cz.acies.organizer.data.persist.Bank;
import cz.acies.organizer.data.persist.BankAccount;
import cz.acies.uniql.sql.SelectQuery;
import cz.acies.uniql.sql.element.UniQLCondition;

public class BankFolderDAO extends MModelFolderDAO
{

	public BankFolderDAO() {}
	
	@Override
	public List<TreeNode> createFolders(List<String> tables) {
		List<TreeNode> data = new ArrayList<TreeNode>();
		try {
			QueryRunner qr = new QueryRunner(this.ds());
			SelectQuery sql = new SelectQuery(dbmd()).addFrom("bank");
			ResultSetHandler rsh = new BeanListHandler(Bank.class);
			List<Bank> banks = qr.query(sql.toSQLString(), rsh);
			for (Bank bank : banks) {
				String id = bank.getId();
				String label = bank.getName();
				TreeNode node = new TreeNode(id, label);
				
				String parentId = bank.getId();
				ResultSetHandler rsh1 = new BeanListHandler(BankAccount.class);
				SelectQuery sql1 = new SelectQuery(dbmd()).addFrom("bank_account")
				.add(new UniQLCondition("parentId", "=", "'"+parentId+"'"));
				
				List<BankAccount> bankAccs = qr.query(sql1.toSQLString(), rsh1);
				appendAccounts(node, bankAccs);
				data.add(node);
			}
		} catch (Exception exc) {
			exc.printStackTrace();
		}
		return data;
	}
	
	private TreeNode appendAccounts(TreeNode parent, List<BankAccount> list) {
		for (BankAccount account : list) {
			String id = account.getId();
			String label = account.getHeader() + " ( " +
				account.getNumber() + "-" + 
				account.getNumber() + "/" + 
				account.getCode() + " )";
			TreeNode node = new TreeNode(id, label);
			parent.addChild(node);
		}
		return parent;
	}
}
